﻿package net.wangit.dev.incrementor;

import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.LockUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;

public class IncrementorUI implements UnitInterceptor {

	public static final String KEY = "net.wangit.dev.incrementor.IncrementorUI.incrementorId";
	private static final String SQL = "select * from INCREMENTOR where iid=?";

	public IncrementorUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String domain = ConsoleDomainUtil.getDomain(ac);
		String source = ac.getRequestParameter("src");
		boolean copy = !Checker.isEmpty(source);
		String iid = copy ? source : ActionContextHelper.getRequest2Session(ac,
				"iid", IncrementorUI.KEY, null);
		String unitShowMode = unit.getShowMode();
		if (!copy && "a".equals(unitShowMode)) {
			String groupId = ac.getRequestParameter("groupid");
			unit.getElement("gid").setDefaultValue(groupId);
		} else if (unit.getData() == null) {
			DB db = DBHelper.getDomainDB(domain);
			MapList data = db.query(IncrementorUI.SQL, iid, 2);
			unit.setData(data);
			if (copy) {
				data.put(0, "iid", "");
				data.put(0, "l", "0");
			}
		}
		LockUtil.setElements(ac, unit, new Object[][] { new Object[] { unit,
				"save" } });
		return unit.write(ac);
	}
}
